<?php

namespace app\admin\behavior;

use app\admin\model\Calendar;
use think\Db;
use think\Exception;

class Workteam
{
	protected $calendarModel = null;

	public function __construct(){
		$this->calendarModel = new Calendar();
	}

    public function workteamTaskAdd($datas)
    {
		$admin_ids = $this->getAdminIds($datas['admin_id'], $datas['admin_ids']);
		$data = [];
		foreach ($admin_ids as $admin_id) {
			$data[] = $this->createDatas($admin_id, $datas);
		}
		if(count($data)>0){
			$this->calendarModel->saveAll($data);
		}
    }

	public function workteamTaskEdit($datas){
		$datas->link = config('admin.crm_url').url('workteam/task/edit',['ids'=>$datas->id]);

		$admin_ids = $this->getAdminIds($datas['admin_id'], $datas['admin_ids']);
		$old_admin_ids = $this->calendarModel->where(['target_type' => 'task', 'target_id' => $datas['id']])->column('admin_id');
		Db::startTrans();
		try{
			// 删除非项目人员
			$this->calendarModel->where(['target_type' => 'task', 'target_id' => $datas['id'], 'admin_id' => ['not in', $admin_ids]])->delete();

			// 修改旧数据
			$new_data = $this->createDatas(0, $datas);
			unset($new_data['admin_id']);
			$this->calendarModel->where(['target_type' => 'task', 'target_id' => $datas['id']])->update($new_data);

			// 新增项目人员
			$new_admin_ids = array_diff($admin_ids, $old_admin_ids);
			if(is_array($new_admin_ids) && count($new_admin_ids)>0){
				$new_datas = [];
				foreach ($new_admin_ids as $admin_id) {
					$new_datas[] = $this->createDatas($admin_id, $datas);
				}
				$this->calendarModel->saveAll($new_datas);
			}

			Db::commit();
			return true;
		}catch (Exception $e){
			Db::rollback();
			return false;
		}
	}

	protected function getAdminIds($admin_id, $admin_ids = ''){
		return array_unique(array_filter(explode(',',$admin_id.','.$admin_ids)));
	}

	protected function createDatas($admin_id, $datas){
		$background = $this->getBackground($datas['level']);
		$status = $this->getstatus($datas['status']);
		$data = [
			'admin_id' => $admin_id,
			'title' => $datas['project_name'] .'-'. $datas['name'],
			'url' => $datas['link'],
			'starttime' => $datas['start_time'],
			'endtime' => $datas['end_time'],
			'background' => $background,
			'classname' => 'btn-dialog',
			'status' => $status,
			'target_type' => 'task',
			'target_id' => $datas['id'],
		];
		return $data;
	}

	protected function getBackground($level){
		$colors = [1 => '#18bc9c', 2 => '#8fc1fe', 3 => '#1688f1', 4 => '#f39c12', 5 => '#f75444'];
		if(isset($colors[$level])){
			return $colors[$level];
		}else{
			return $colors[0];
		}
	}

	protected function getStatus($status){
		switch($status){
			case -1:
				$status_text = 'expired';
				break;
			case 2:
				$status_text = 'completed';
				break;
			default:
				$status_text = 'normal';
				break;
		}
		return $status_text;
	}
}
